/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

// ......
package GUI;

import Control.Control;
import DataBase.GlobalException;
import DataBase.NoDataException;
import DataBase.ServicioMenu;
import Logic.Clasificacion;
import Logic.Log;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author LiN
 */
public class GUI_Users extends javax.swing.JPanel {
    Control control=Control.getInstance();
    /**
     * Creates new form GUI_Users
     */
    public GUI_Users() {
        initComponents();
       this.jTable1.getTableHeader().setReorderingAllowed(false);
       this.jTable2.getTableHeader().setReorderingAllowed(false);
       this.jTable3.getTableHeader().setReorderingAllowed(false);
        if(control.getSELECTED_SERVER()!=""){
            loadUsers();
            loadRoles();
        }
    }
    
    public void clearTable(JTable jtable){
        while(jtable.getRowCount()>0){
            ((DefaultTableModel)jtable.getModel()).removeRow(0);
        }
    }
    public void loadRoleUser(){
        clearTable(jTable3);
        ServicioMenu sm=control.getServicioMenu();
        ArrayList<String> list=(ArrayList<String>) sm.listarRolesDeUsuario(this.jTextField1.getText());
        Iterator ite=list.iterator();
        
        while(ite.hasNext()){
            ((DefaultTableModel)this.jTable3.getModel()).addRow(new Object[]{ite.next()});
        }
    }
    public void loadUsers(){
        clearTable(jTable1);
        ServicioMenu sm=control.getServicioMenu();
        ArrayList<String> list=(ArrayList<String>) sm.listarUsers();
        
        Iterator ite=list.iterator();
        while(ite.hasNext()){
            ((DefaultTableModel)this.jTable1.getModel()).addRow(new Object[]{ite.next()});
        }
    }
    public void loadRoles(){
        clearTable(jTable2);
        Iterator ite=control.getClasificaciones().iterator();
        while(ite.hasNext()){
            Clasificacion aux=(Clasificacion) ite.next();
            ((DefaultTableModel)this.jTable2.getModel()).addRow(new Object[]{aux.getNombreRol(),aux.getDescripcion()});
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        deleteButton = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTable3 = new javax.swing.JTable();
        jButton3 = new javax.swing.JButton();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Users Catalog"));

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "User Name"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jTable1MouseReleased(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        deleteButton.setText("Delete");
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });

        jButton2.setText("New");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(0, 137, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(deleteButton))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 424, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(deleteButton)
                    .addComponent(jButton2)))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Clasifications"));

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Classification", "Description"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable2MouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(jTable2);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 337, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 453, Short.MAX_VALUE)
        );

        jLabel1.setText("User:");

        jTextField1.setEditable(false);

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Current Classifications"));

        jTable3.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Classification"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane3.setViewportView(jTable3);

        jButton3.setText("Unassign");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(0, 182, Short.MAX_VALUE)
                .addComponent(jButton3))
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 398, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton3))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        new GUI_NewUser(this);
    }//GEN-LAST:event_jButton2ActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
       if(jTable1.getSelectedRowCount()>0){
           ServicioMenu sm=control.getServicioMenu();
           String user=(String) ((DefaultTableModel)jTable1.getModel()).getValueAt(jTable1.getSelectedRow(),0);
           boolean status;
           try {
               status=sm.dropUser(user);
           
               //Logs
                Log log = new Log(new Date(),control.getUser(),control.getSELECTED_SERVER(),Log.DELETE_USER,"Delete user: "+user);
                control.insertLog(log);
                control.saveLogs();
               
               JOptionPane.showMessageDialog(null,"User Deleted.....");
               
               this.loadUsers();
               
           } catch (   SQLException | ClassNotFoundException ex) {
               Logger.getLogger(GUI_Users.class.getName()).log(Level.SEVERE, null, ex);
           }
       }
    }//GEN-LAST:event_deleteButtonActionPerformed

    private void jTable1MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseReleased
        this.jTextField1.setText((String) ((DefaultTableModel)jTable1.getModel()).getValueAt(jTable1.getSelectedRow(),0));
        this.loadRoleUser();
    }//GEN-LAST:event_jTable1MouseReleased

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        if(this.jTable3.getSelectedRowCount()>0){
            int val=JOptionPane.showConfirmDialog(null,"Are you sure?","Confirm",JOptionPane.YES_NO_OPTION);
            if(val==0){
                String aux=(String) ((DefaultTableModel)this.jTable3.getModel()).getValueAt(jTable3.getSelectedRow(),0);
                ServicioMenu sm=control.getServicioMenu();
                try {
                    sm.removeCategoryFromUser(aux,this.jTextField1.getText());
                    
                    
                    //Logs
                    Log log = new Log(new Date(),control.getUser(),control.getSELECTED_SERVER(),Log.UNASSIGN_CLASSIFICATION,"Unassigned Classification "+aux+" from "+this.jTextField1.getText());
                    control.insertLog(log);
                    control.saveLogs();
                    
                    this.loadRoleUser();
                    
                    JOptionPane.showMessageDialog(null,"Classification unassigned...!!!");
                } catch (    GlobalException | NoDataException ex) {
                    Logger.getLogger(GUI_Users.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jTable2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable2MouseClicked
        if(evt.getClickCount()>=2){
            int val=JOptionPane.showConfirmDialog(null,"Are you sure?","Confirm",JOptionPane.YES_NO_OPTION);
            if(val==0){
                String aux=(String)((DefaultTableModel)this.jTable2.getModel()).getValueAt(jTable2.getSelectedRow(),0);
                ServicioMenu sm=control.getServicioMenu();
                
                try {
                    sm.grantPrivilege(aux,this.jTextField1.getText());
                    sm.grantPrivilege(" all on t5 ",this.jTextField1.getText());
                    sm.grantPrivilege(" all on t6 ",this.jTextField1.getText());
                    //Logs
                    Log log = new Log(new Date(),control.getUser(),control.getSELECTED_SERVER(),Log.ASSIGN_CLASSIFICATION,"Assigned Classification "+aux+" to "+this.jTextField1.getText());
                    control.insertLog(log);
                    control.saveLogs();
                    
                    this.loadRoleUser();
                    JOptionPane.showMessageDialog(null,"Classification "+aux+" assigned to "+jTextField1.getText());
                } catch (        SQLException | ClassNotFoundException ex) {
                    Logger.getLogger(GUI_Users.class.getName()).log(Level.SEVERE, null, ex);
                }                
            }
        }
    }//GEN-LAST:event_jTable2MouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton deleteButton;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JTable jTable3;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
